const util = require('../../utils/util.js')
const app = getApp()
const { markreadList, removeThreemonthdataList } = require('../../api/geData.js')
Page({
  /**
   * 页面的初始数据
   */
  data: {
    newsData: [ // 系统通知
    ],
    privateletterData: [],// 私信通知
    newsNum: 0,
    privateletterNum:0,
    refresh: false,
    goBool: true,
    compareData: {
      packId: null,
      courseId: null
    },
    currentTab:0,
    userInfo:'',
    unreadnewsNumber: '', 
    unreadletterNumber:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    app.globalData.chooseNewsMsg = false // 把控制全局请求信息栏的变量设为false 其他页面就不会再请求查看信息栏
    // this.getData();
    this.setData({
      refresh: true
    })
    this.getData()
  },
  goGrade(e) {
    if (this.data.goBool) {
      this.setData({
        goBool: false
      })
    } else {
      return
    }
    let dataObj = e.currentTarget.dataset.set;

    let id = dataObj.id,
      newsData = this.data.newsData,
      privateletterData = this.data.privateletterData,
      num = 0,
      msgStatus = null

    wx.showLoading({
      title: '加载中',
    })
    let that = this
    // if(this.data.currentTab=='0'){
      newsData.forEach(item => {
        if (item.id == id) {
          msgStatus = item.status // 状态码给status后面做判断
          wx.request({
            url: app.globalData.baseUrl + "/gmessage/update",
            data: {
              id: id,
              status: '1'
            },
            method: 'POST',
            header: {
              "Content-Type": "application/json"
            },
            success(res) {
              if (res.data.code == '0') {
                that.setData({
                  goBool: true
                })
                that.getData()
              }
            }
          })

          item.showRadio = false
          if (this.data.newsNum > 0) {
            this.data.newsNum--
          }
          app.setTabBarBadge(this.data.newsNum + '')
        }
      })
    // }else if(this.data.currentTab=='1'){
    //   privateletterData.forEach(item => {
    //     if (item.id == id) {
    //       msgStatus = item.status // 状态码给status后面做判断
    //       wx.request({
    //         url: app.globalData.baseUrl + "/gmessage/update",
    //         data: {
    //           id: id,
    //           status: '1'
    //         },
    //         method: 'POST',
    //         header: {
    //           "Content-Type": "application/json"
    //         },
    //         success(res) {
    //           if (res.data.code == '0') {
    //             that.setData({
    //               goBool: true
    //             })
    //             that.getletterData()
    //           }
    //         }
    //       })

    //       item.showltRadio = false
    //       if (this.data.privateletterNum > 0) {
    //         this.data.privateletterNum--
    //       }
    //       app.setTabBarBadge(this.data.privateletterNum + '')
    //     }
    //   })
    // }
    //type为4
    if (dataObj.type == '4') {
      wx.hideLoading()
      wx.navigateTo({
        url: '/pages/detail/detailGrade/detailGrade?coursename=' + dataObj.courseName + '&status=0'
      })
      return
    }
    // type为8的时候跳转到问卷
    if (dataObj.type == '8') {
      let status = '';
      if (dataObj.quesSurvey.isReply != '0') {
        //已回复
        wx.navigateTo({
          url: '/pages/questionnaire/detailDone?pid=' + dataObj.quesSurvey.id + '&id=' + dataObj.quesSurvey.questionnaire.id
        })
        return;
      } else if (dataObj.quesSurvey.questionnaireState == '0') {
        //未完成
        status = '0'
      } else {
        //已撤回
        status = '2'
      }
      wx.navigateTo({
        url: '/pages/questionnaire/detail?pid=' + dataObj.quesSurvey.id + '&id=' + dataObj.quesSurvey.questionnaire.id + '&status=' + status
      })
      return
    }
    //type为9跳转到心路旅程
    if (dataObj.type == '9') {
      wx.navigateTo({
        url: '/pages/H5process/H5process'
      })
      return
    }
    //type为10跳转到加入就业详情页面
    if (dataObj.type == '10') {
      // console.log(dataObj)
      wx.navigateTo({
        url: '/pages/detail/joinJobgroup/joinJobgroup?teacherName=' + dataObj.teacherName + '&teamName=' + dataObj.teamName + '&QQ=' + dataObj.qq
      })
      return
    }

    //type为11退出就业小组
    if (dataObj.type == '11' || dataObj.type == '14' || dataObj.type == '15' || dataObj.type == '13'){
      wx.hideLoading()
      return
    }

    dataObj.type == '6' && (dataObj.type ='2')
  
    //消息通知type为16跳转到国科课堂首页
    if (dataObj.type == '16') {
      wx.hideLoading()
      let userInfo = wx.getStorageSync('userInfo')
      this.setData({
        userInfo: userInfo
      })
      return
    }

    let unitClass = [dataObj.type, 'courseid', 'classid', 'formalclassid']
    this.toGradeDetail(dataObj, unitClass[0], unitClass[dataObj.type], msgStatus, dataObj.packid)
    this.setData({
      newsData: newsData,
      privateletterData: privateletterData
    })
  },
  toGradeDetail(dataObj, type, name, msgStatus, packId) {
    let that = this
    let urlArr = ['', '/pages/detail/agreeGrade/agreeGrade', '/pages/period/confirmPeriod/confirmPeriod', '/pages/period/coursePeriod/coursePeriod']
    wx.request({
      url: app.globalData.baseUrl + '/findMyClass',
      data: {
        stu_id: wx.getStorageSync("userInfo").cluesOrStuId
      },
      method: 'POST',
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success(res) {
        if (res.data.code == 0) {
          let myPackList = res.data.data.myPackList
          let idx = myPackList.length,
              num = 0
          if (myPackList.length == 0) {
            that._goPage.call(that, '0', '0', '?coursename=""&status=0')
            return
          }
          myPackList.map((item, index) => {
            if (item[name] == dataObj[name] && item.packId == packId) {
              const {
                courseid,
                formalclassid,
                classid,
                noticeId,
                coursename,
                formalClassName,
                status,
                begintime,
                endtime,
                show,
                selTimeBegin,
                selTimeEnd
              } = item;
              const noticeType = item.noticeType ? item.noticeType : 0
              // console.log(noticeType)
              that.setData({
                compareData: {
                  packId: packId,
                  courseId: courseid
                }
              })
              /* 参数处理，勿动 */
              const startTime = util.formatTime(begintime && begintime || selTimeBegin, 1).split(' ')[0]
              const endTime = util.formatTime(endtime && endtime || selTimeEnd, 1).split(' ')[0]

              const passData = {
                statusId: status,
                courseName: coursename,
                formalClassName: formalClassName,
                startTime: startTime,
                endTime: endTime,
                time: startTime + '至' + endTime,
                courseId: courseid,
                packId:packId,
                classid: classid,
                noticeId: noticeId,
                formalclassid: formalclassid,
                isJobCourse: (noticeType == 1 && true || false)
              }
              wx.setStorageSync("passData", passData)
              /* 页面传参 */
              let paramsUrl = `?courseid=${courseid}&formalclassid=${formalclassid}&classid=${classid}&coursename=${coursename}&status=${status}&begintime=${begintime}&endtime=${endtime}`
              that._goPage.call(that, item.status, type, paramsUrl, passData)

            } else {
              num ++
              if (num != idx) return
              that._goPage.call(that,'0', '0','?coursename=""&status=0')
            }
          })
        }
      }
    })
  },
  _goPage(courseStatus, type, paramsUrl, passData) {
    let url = null
    switch (courseStatus) {
      case '1': // 未确认
        let grade = wx.getStorageSync('agreeGrade');
        if(passData.isJobCourse){
          url = '/pages/period/selectPeriod/selectPeriod?showQuick=0'
        } else {
          if ((!!grade && grade.packId == this.data.compareData.packId) && (!!grade && grade.courseId == this.data.compareData.courseId) && grade.noticeId == this.data.compareData.noticeId) {
            url = '/pages/period/selectPeriod/selectPeriod?showQuick=0'
          } else {
            url = '/pages/detail/agreeGrade/agreeGrade'
          }
        }
        break
      case '2': // 已确认
        url = '/pages/detail/waitGrade/waitGrade?showTextIndex=0&showBtn=0'
        break
      case '3': // 已确认
        url = '/pages/detail/waitGrade/waitGrade?showTextIndex=0&showBtn=0'
        break
      case '4': // 已排班
        url = '/pages/period/confirmPeriod/confirmPeriod'
        break
      case '5': // 待开班
        url = '/pages/detail/waitGrade/waitGrade?showTextIndex=1&showBtn=0'
        break
      case '6': // 已开班
        url = `/pages/period/coursePeriod/coursePeriod`
        break
      // case '7': // 已开班
      //   console.log('666')
      //   url = `/pages/period/coursePeriod/coursePeriod`
      //   break
      

        // 没有default
    }

    if (courseStatus * 1 >= 4 && type == '1') { // 课程状态大于4 让type = 1信息那条跳转到下面的url
      url = '/pages/detail/waitGrade/waitGrade?showTextIndex=0&showBtn=0'
    }
    if (courseStatus * 1 > 6 && type == '2') {
      url = '/pages/detail/waitGrade/waitGrade?showTextIndex=1&showBtn=0'
    } else if (courseStatus == '7' && type == '3') {
      url = `/pages/detail/detailGrade/detailGrade${paramsUrl}`
    } else if (courseStatus == '0' && type == '0'){
      url = `/pages/detail/detailGrade/detailGrade${paramsUrl}`
    }
    
    wx.hideLoading()
    wx.navigateTo({
      url: url,
    })
  },
  // 获取消息通知数据函数
  getData() {
    let _this = this
    wx.showLoading({
      title: '加载中...',
    })
    wx.request({
      url: app.globalData.baseUrl + "/gmessage/findGmessageList",
      // url: "http://192.168.2.39:8080/gmessage/findGmessageList?",
      data: {
        telephone: wx.getStorageSync('userInfo').account,
        status: '',
        gmessageType: '',
        from: '0',
        source:''
      },
      method: "POST",
      header: {
        "Content-Type": "application/json"
      },
      success(res) {
        let data = res.data.data.gmessageList,
          unreadnewsNumber = res.data.data.unreadNumber;
        _this.data.newsNum = 0
        data.forEach(val => {
          let time = util.formatTime(val.createdAt, 1)
          val.time = time
          if (val.status == "0") {
            val.showRadio = true
            _this.data.newsNum++
          }
          let valnr = _this.convertHtmlToText(val.content)
          val.newContent = valnr
        })
        wx.hideLoading()
        // console.log(res)
        _this.setData({
          newsData: data,
          unreadnewsNumber: unreadnewsNumber
        })
        app.setTabBarBadge(_this.data.newsNum + '')
        // console.log(_this.data.newsNum)
      }
    })
  },
  // 获取私信通知数据函数
  getletterData(){
    let _this = this 
    wx.request({
      url: app.globalData.baseUrl + "/gmessage/findGmessageList",
      data: {
        telephone: wx.getStorageSync('userInfo').account,
        status: '',
        gmessageType: '1',
        from: '0'
      },
      method: "POST",
      header: {
        "Content-Type": "application/json"
      },
      success(res) {
        let data = res.data.data.gmessageList,
          unreadletterNumber = res.data.data.unreadNumber;
        _this.data.privateletterNum = 0
        data.forEach(val => {
          let time = util.formatTime(val.createdAt, 1)
          val.time = time
          if (val.status == "0") {
            val.showltRadio = true
            _this.data.privateletterNum++
          }
        })
        wx.hideLoading()
        _this.setData({
          privateletterData: data,
          unreadletterNumber: unreadletterNumber
        })
        app.setTabBarBadge(_this.data.privateletterNum + '')
        // console.log(_this.data.privateletterNum)
      }
    })
  },

  // 消息列表切换
  switchnewsTab(e) {
    // console.log(e);
    let that = this;
    if (this.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      that.setData({
        currentTab: e.target.dataset.current,
      })
    }
  },
  swiperChange: function (e) {
    this.setData({
      currentTab: e.detail.current,
    })
    if (this.data.currentTab == '0') {
     this.getData()
    } else if (this.data.currentTab == '1') {
      this.getletterData()
    }
  },
// 点击全部已读
markallReadList(){
  let _this=this
  // if(this.data.currentTab=='0'){
    wx.showModal({
      content: '此操作会将未读的动态提醒全部标记为已读',
      cancelText: '取消',
      confirmText:'全部已读',
      confirmColor:'#2A8EFF',
      success(res) {
        if (res.confirm) {
          if (_this.data.unreadnewsNumber=='0') return 
          markreadList(wx.getStorageSync('userInfo').account, 0, 0).then(res => {
            _this.getData()
          })
        }
      }
    })
  // }else if(this.data.currentTab=='1')
  // {
  //   wx.showModal({
  //     content: '此操作会将未读的动态提醒全部标记为已读',
  //     cancelText: '取消',
  //     confirmText: '全部已读',
  //     confirmColor: '#2A8EFF',
  //     success(res) {
  //       if (res.confirm) {
  //         if (_this.data.unreadletterNumber == '0') return
  //       markreadList(wx.getStorageSync('userInfo').account, 1, 0).then(res => {
  //       _this.getletterData()
  //       })
  //     }
  //     }
  // })
  // }
},
removethreemonthNew(){
  removeThreemonthdataList(wx.getStorageSync('userInfo').account, 0, 0).then(res => { 
  })
},
removethreemonthPrivateletter() {
  removeThreemonthdataList(wx.getStorageSync('userInfo').account, 1, 0).then(res => {
  })
},
convertHtmlToText(inputText) {
    var returnText = "" + inputText;
    returnText = returnText.replace(/<\/div>/ig, '\r\n');
    returnText = returnText.replace(/<\/li>/ig, '\r\n');
    returnText = returnText.replace(/<li>/ig, '  *  ');
    returnText = returnText.replace(/<\/ul>/ig, '\r\n');
    //-- remove BR tags and replace them with line break
    returnText = returnText.replace(/<br\s*[\/]?>/gi, "\r\n");

    //-- remove P and A tags but preserve what's inside of them
    returnText = returnText.replace(/<p.*?>/gi, "\r\n");
    returnText = returnText.replace(/<a.*href="(.*?)".*>(.*?)<\/a>/gi, " $2 ($1)");

    //-- remove all inside SCRIPT and STYLE tags
    returnText = returnText.replace(/<script.*>[\w\W]{1,}(.*?)[\w\W]{1,}<\/script>/gi, "");
    returnText = returnText.replace(/<style.*>[\w\W]{1,}(.*?)[\w\W]{1,}<\/style>/gi, "");
    //-- remove all else
    returnText = returnText.replace(/<(?:.|\s)*?>/g, "");

    //-- get rid of more than 2 multiple line breaks:
    returnText = returnText.replace(/(?:(?:\r\n|\r|\n)\s*){2,}/gim, "\r\n\r\n");

    //-- get rid of more than 2 spaces:
    returnText = returnText.replace(/ +(?= )/g, '');

    //-- get rid of html-encoded characters:
    returnText = returnText.replace(/ /gi, " ");
    returnText = returnText.replace(/&/gi, "&");
    returnText = returnText.replace(/"/gi, '"');
    returnText = returnText.replace(/</gi, '<');
    returnText = returnText.replace(/>/gi, '>');

    return returnText;
  },
  // 下拉刷新
  onPullDownRefresh: function() {
    this.getData();
    setTimeout(() => {
      wx.stopPullDownRefresh();
    }, 500)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onShow: function() {
    if (this.data.refresh)  // 首页进来不用请求 等onShow的时候再请求
    this.removethreemonthNew();
    this.removethreemonthPrivateletter();
    this.setData({
      refresh: true
    })

  },
})